package com.web.session;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * 验证码：图片验证码
 */
@WebServlet("/checkImg")
public class CheckImage extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int width = 160;
        int height = 30;
        BufferedImage bufi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 通过图片缓冲区，得到画笔,使用平面方式
        Graphics2D g = (Graphics2D) bufi.getGraphics();
        // 设置图片的背景颜色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        Random r = new Random();
        // 设置画笔的颜色
        for (int i = 0; i < 100; i++) {
            g.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
            // 画椭圆，长半轴和短半轴为零，画点
            g.drawOval(r.nextInt(width), r.nextInt(height), 0, 0);
        }
        // 画线
        for (int i = 0; i < 10; i++) {
            g.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
            // 画线
            g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
        }
        // 随机写一些验证码符号
        String datas = "QWERTYUPASDFGHJKLZXCVBNMqwertyuopasdfghjkzxcvbnm0123456789";
        // 设置画的字符的位置
        int x = 25;
        // 需要定义字符串缓冲区，存储给图片上书写的随机验证码
        StringBuilder sb = new StringBuilder();
        //String img = "";
        for (int i = 0; i < 4; i++) {
            g.setColor(new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
            // 随机取出一个字符
            char ch = datas.charAt(r.nextInt(datas.length()));
            sb.append(ch);
            //img += ch;
            // 需要设置字体的大小，
            g.setFont(new Font("宋体", Font.BOLD, 26));
            // 给图片上写字符
            g.drawString(ch + "", x, 25);
            x += 35;
        }
        // 需要将验证码存储到session中
        req.getSession().setAttribute("randomImg" ,sb.toString());
        // 关于给客户端响应不同的文件的时候，对应的类型可以在tomcat的conf/web.xml 文件中查找
        resp.setContentType("image/jpeg");
        ImageIO.write(bufi, "jpeg", resp.getOutputStream());
    }
}
